package io.tim.mvc.form;

import java.lang.reflect.Field;

import javax.servlet.http.HttpServletRequest;

import io.tim.mvc.form.ActionForm;

/**
 * 根据传入的具体业务的 form 类名通过反射实例化 Form 类的实例，并根据 HttpServletRequest 填充 Form 实例的属性
 * 
 * @author Zhang Nan
 * @since 2017/02/21
 *
 */
public class FormBuilder {

	public FormBuilder() {

	}

	public static ActionForm build(String formName, HttpServletRequest request) {
		ActionForm aForm = null;
		try {

			Class<?> cls = Class.forName(formName);
			aForm = (ActionForm) cls.newInstance();
			Field[] fields = cls.getDeclaredFields();

			for (Field f : fields) {
				// 私有属性需要先设置可访问
				f.setAccessible(true);
				f.set(aForm, request.getParameter(f.getName()));
				f.setAccessible(false);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return aForm;
	}

}
